﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ITProject.Repository.Abstract;
using ITProject.Repository.Concrete;
using ITProject.Domain.Entities;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Win32;
using SharpSvn;
using SharpSvn.UI;
using ITProject.Domain.Enums;

namespace SVNClient
{
    /// <summary>
    /// Interaction logic for SVNMainContent.xaml
    /// </summary>
    public partial class SVNMainContent : UserControl
    {
        public string userLogin;
        private int projectId;
        private IProjectRepository _projectRepository;
        private ISVNRepository _SVNRepository;
        private IUserRepository _userRepository;
        string projectPath;

        public SVNMainContent()
        {
            InitializeComponent();
        }

        public SVNMainContent(string login, int projectId)
        {
            InitializeComponent();
            userLogin = login;
            this.projectId = projectId;
            App.Current.MainWindow.SizeChanged += new SizeChangedEventHandler(MainWindow_SizeChanged);
            _projectRepository = new ProjectRepository();
            _SVNRepository = new SVNRepository();
            _userRepository = new UserRepository();
            Project project = _projectRepository.GetProjectById(projectId);
            ProjectNameTextBlock.Text = project.Name;
            ProjectDescriptionTextBlock.Text = project.Description;
            var projectsxmldata = ReadFromXml();
            if (projectsxmldata == null || projectsxmldata.Count == 0)
            {
                var result = MessageBox.Show("Wybierz lokalizację dla projektu");
                if (result == MessageBoxResult.OK)
                {
                    using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog())
                    {
                        dlg.Description = "Wybierz folder";
                        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            projectsxmldata = new List<ProjectXMLData>();
                            projectsxmldata.Add(new ProjectXMLData
                            {
                                Id = projectId,
                                Name = project.Name,
                                ProjectPath = dlg.SelectedPath
                            });
                            label1.Content = projectPath = dlg.SelectedPath;
                            SavetoXml(projectsxmldata);
                        }
                    }
                }
            }
            else
            {
                if (projectsxmldata.Where(x => x.Id == projectId).Any())
                {
                    label1.Content = projectPath = projectsxmldata.Where(x => x.Id == projectId).FirstOrDefault().ProjectPath;

                }
                else
                {
                    using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog())
                    {
                        dlg.Description = "Wybierz folder";
                        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            projectsxmldata.Add(new ProjectXMLData
                            {
                                Id = projectId,
                                Name = project.Name,
                                ProjectPath = dlg.SelectedPath
                            });
                            label1.Content = projectPath = dlg.SelectedPath;
                            SavetoXml(projectsxmldata);
                        }
                    }
                }
            }
        }

        void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.Width = App.Current.MainWindow.Width;
            this.Height = App.Current.MainWindow.Height;
        }

        List<ProjectXMLData> ReadFromXml()
        {
            try
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(List<ProjectXMLData>));
                TextReader textReader = new StreamReader("projects.xml");
                List<ProjectXMLData> projects;
                projects = (List<ProjectXMLData>)deserializer.Deserialize(textReader);
                textReader.Close();
                return projects;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        void SavetoXml(List<ProjectXMLData> projects)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<ProjectXMLData>));

            using (StreamWriter sw = new StreamWriter("projects.xml"))
            {
                serializer.Serialize(sw, projects);
            }
        }

        private void GetLatestVersionButton_Click(object sender, RoutedEventArgs e)
        {
            using (SvnClient client = new SvnClient())
            {
                try
                {
                    string uri = @"file:///D:/SVN/" + ProjectNameTextBlock.Text;
                    SvnCheckOutArgs arguments = new SharpSvn.SvnCheckOutArgs();
                    SvnUpdateResult result;
                    string dir = label1.Content.ToString();
                    SvnUriTarget target = new SharpSvn.SvnUriTarget(uri);
                    client.CheckOut(target, dir, arguments, out result);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
        }

        private void CommitButton_Click(object sender, RoutedEventArgs e)
        {
            SvnCommitArgs commitArgs = new SharpSvn.SvnCommitArgs();
            commitArgs.LogMessage = "testowy commit";
            SvnCommitResult commitResult;
            string uri = @"file:///D:/SVN/" + ProjectNameTextBlock.Text;

            using (SvnClient client = new SharpSvn.SvnClient())
            {
                try
                {
                    SvnUIBindArgs bindArgs = new SvnUIBindArgs();

                    //"E:/testfile.txt"SvnUI.Bind(client, bindArgs );
                    SvnUriTarget target = new SharpSvn.SvnUriTarget(uri);
                    //commitArgs.ta
                    client.Commit(label1.Content.ToString(), commitArgs, out commitResult);
                    if (commitResult != null)
                    {
                        Console.WriteLine("Successfully commited revision " + commitResult.Revision);
                        User user = _userRepository.GetUserByLogin(userLogin);
                        _SVNRepository.AddSVNHistory(new SVNHistory
                        {
                            CreateDate = DateTime.Now,
                            ProjectId = projectId,
                            UserId = user.Id,
                            Type = (int)SVNOperation.COMMIT,
                            Description = "Rev " + commitResult.Revision.ToString() + ": " + CommitText.Text
                        });
                    }
                    else
                        MessageBox.Show("Aktualna wersja jest zgodna z wersją z repozytorium");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            //try
            {
                SvnClient Client = new SvnClient();
                OpenFileDialog fl = new OpenFileDialog();
                fl.InitialDirectory = projectPath;
                fl.ShowDialog();
                SvnAddArgs a = new SvnAddArgs();
                a.Depth = SvnDepth.Empty;
                Client.Add(fl.FileName, a);
                User user = _userRepository.GetUserByLogin(userLogin);
                var tempFile = new System.IO.FileInfo(fl.FileName);
                SVNHistory history = new SVNHistory
                {
                    CreateDate = DateTime.Now,
                    ProjectId = projectId,
                    UserId = user.Id,
                    Filename = tempFile.Name,
                    Type = (byte)SVNOperation.ADD
                };
                _SVNRepository.AddSVNHistory(history);
            }
            //catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }
    }
}
